import WebSocket from 'ws';
import http from 'http';
import net from 'net';
import { randomBytes } from 'crypto';
import path from 'path';

// 创建HTTP服务器
const server = http.createServer();

// 创建WebSocket服务器
const wss = new WebSocket.Server({ noServer: true });

// 处理WebSocket升级
server.on('upgrade', (request: http.IncomingMessage, socket: net.Socket, head: Buffer) => {
  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit('connection', ws, request);
  });
});

// 处理WebSocket连接
wss.on('connection', (ws: WebSocket, request: http.IncomingMessage) => {

  console.log('New WebSocket connection established');

  // 处理收到的消息
  ws.on('message', async (messageContent: string) => {
    console.log('Received message:', message);
    ws.send(JSON.stringify({
      cmd: 'Show Text',
      message: 'Hello World!'
    }));
  });

  // 处理连接关闭
  ws.on('close', (code: number) => {
    console.log("Connection closed");
  });

  // 处理错误
  ws.on('error', (error: Error) => {
    console.error("Connection error");
  });
});


// 启动服务器，监听8080端口
const PORT = 8080;
server.listen(PORT, () => {
  console.log(`WebSocket server running on ws://localhost:${PORT}`);
  console.log('Authentication is required for all connections');
});